package com.jxs.android.sxyw;

import java.io.IOException;
import java.util.ArrayList;
import java.util.Date;

import org.ksoap2.serialization.SoapObject;
import org.ksoap2.serialization.SoapSerializationEnvelope;
import org.xmlpull.v1.XmlPullParserException;

import android.app.ProgressDialog;
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.jxs.android.soap.BuWebService;
import com.jxs.android.soap.IWebService;
import com.jxs.android.sxyw.boot.SelfApplication;
import com.jxs.android.sxyw.weiget.PopMsg;
import com.jxs.android.sxyw.weiget.TopBar;
import com.jxs.android.util.StartHelper;
import com.jxs.android.util.StringUtils;

public class DangerSubmit extends AbstractActivity implements OnClickListener {

	private static final int REQUEST_CODE_GET_SUBJECT = 0x8873;
	private static final int REQUEST_CODE_GET_GRADE = 0x8874;
	private static final int REQUEST_CODE_GET_BUSINESS = 0x8875;
	private static final int REQUEST_CODE_GET_PHOTO = 0x5573;
	private static final int REQUEST_CODE_GET_LOACTION = 0x8877;
	private static final int REQUEST_CODE_GET_DECRIPTON = 0x8878;
	private static final int REQUEST_CODE_GET_STATION = 0x8879;
	private static final int REQUEST_CODE_GET_ORG = 0x8880;
	private static final int REQUEST_CODE_TO_UPLOAD_PIC = 0x99901;
	private String subject = "";
	private String station = "";
	private String latitude = "";
	private String longitude = "";
	private String desc = "";
	private String grade_id = "";
	private String business_id = "";
	private String city_id = "";
	private String country_id = "";
	private ProgressDialog progressDialog;

	private ArrayList<String> fileNames = new ArrayList<String>();

	private TextView danger_info_subject,// 主题
			danger_info_grade_name// 隐患程度
			, danger_info_business_name// 业务
			, danger_info_city_country// 市县区
			, danger_info_station_name// 站点
			, danger_info_description// 描述
			, danger_info_location// 坐标
			, danger_info_photo// 图片
			, danger_info_person// 上报人
			, danger_info_updated// 上报时间
			;

	private LinearLayout danger_info_subject_ll, danger_info_business_name_ll, danger_info_grade_name_ll, danger_info_station_name_ll, danger_info_photo_ll, danger_info_description_ll, danger_info_location_ll, danger_info_city_country_ll;
	private Context context;

	protected void onCreate(android.os.Bundle savedInstanceState) {
		this.context = this;
		initTopBar(savedInstanceState, R.layout.danger_submit);

		danger_info_subject = (TextView) findViewById(R.id.danger_info_subject);
		danger_info_grade_name = (TextView) findViewById(R.id.danger_info_grade_name);
		danger_info_business_name = (TextView) findViewById(R.id.danger_info_business_name);
		danger_info_city_country = (TextView) findViewById(R.id.danger_info_city_country);
		danger_info_station_name = (TextView) findViewById(R.id.danger_info_station_name);
		danger_info_location = (TextView) findViewById(R.id.danger_info_location);
		danger_info_description = (TextView) findViewById(R.id.danger_info_description);
		danger_info_photo = (TextView) findViewById(R.id.danger_info_photo);
		danger_info_person = (TextView) findViewById(R.id.danger_info_person);
		danger_info_updated = (TextView) findViewById(R.id.danger_info_updated);

		danger_info_subject_ll = (LinearLayout) findViewById(R.id.danger_info_subject_ll);
		danger_info_grade_name_ll = (LinearLayout) findViewById(R.id.danger_info_grade_name_ll);
		danger_info_photo_ll = (LinearLayout) findViewById(R.id.danger_info_photo_ll);
		danger_info_station_name_ll = (LinearLayout) findViewById(R.id.danger_info_station_name_ll);
		danger_info_description_ll = (LinearLayout) findViewById(R.id.danger_info_description_ll);
		danger_info_location_ll = (LinearLayout) findViewById(R.id.danger_info_location_ll);
		danger_info_business_name_ll = (LinearLayout) findViewById(R.id.danger_info_business_name_ll);
		danger_info_city_country_ll = (LinearLayout) findViewById(R.id.danger_info_city_country_ll);
		danger_info_grade_name_ll.setOnClickListener(this);
		danger_info_photo_ll.setOnClickListener(this);
		danger_info_subject_ll.setOnClickListener(this);
		danger_info_station_name_ll.setOnClickListener(this);
		danger_info_description_ll.setOnClickListener(this);
		danger_info_location_ll.setOnClickListener(this);
		danger_info_business_name_ll.setOnClickListener(this);
		danger_info_city_country_ll.setOnClickListener(this);

		danger_info_person.setText(SelfApplication.getUserInfo().getUser_name());
		danger_info_updated.setText(SDF_YYYY_MM_dd_HH_mm.format(new Date()));

	}

	@Override
	public void onClick(View v) {
		if (v.getId() == danger_info_photo_ll.getId()) {
			Intent intent = new Intent(this, SelectPic.class);
			Bundle bundle = new Bundle();
			bundle.putStringArrayList("fileNames", fileNames);
			intent.putExtras(bundle);
			startActivityForResult(intent, REQUEST_CODE_GET_PHOTO);
		} else if (v.getId() == danger_info_grade_name_ll.getId()) {
			Intent intent = new Intent(this, SelectGrade.class);
			startActivityForResult(intent, REQUEST_CODE_GET_GRADE);
		} else if (v.getId() == danger_info_business_name_ll.getId()) {
			Intent intent = new Intent(this, SelectBusiness.class);
			startActivityForResult(intent, REQUEST_CODE_GET_BUSINESS);
		} else if (v.getId() == danger_info_subject_ll.getId()) {
			requestEditText("主题", subject, REQUEST_CODE_GET_SUBJECT, 50);
		} else if (v.getId() == danger_info_station_name_ll.getId()) {
			requestEditText("站点名称", station, REQUEST_CODE_GET_STATION, 50);
		} else if (v.getId() == danger_info_description_ll.getId()) {
			requestEditText("描述信息", desc, REQUEST_CODE_GET_DECRIPTON, 300);
		} else if (v.getId() == danger_info_location_ll.getId()) {
			Intent intent = new Intent(context, StandardStatecraft.class);
			startActivityForResult(intent, REQUEST_CODE_GET_LOACTION);
		} else if (v.getId() == danger_info_city_country_ll.getId()) {
			Intent intent = new Intent(context, SelectOrg.class);
			startActivityForResult(intent, REQUEST_CODE_GET_ORG);
		}

	}

	private void validationAndSubmit() {
		if (StringUtils.isEmpety(subject)) {
			PopMsg.show("请填写主题!");
		} else if (StringUtils.isEmpety(grade_id)) {
			PopMsg.show("请选择隐患程度!");
		} else if (StringUtils.isEmpety(business_id)) {
			PopMsg.show("请选择业务!");
		} else if (StringUtils.isEmpety(city_id)) {
			PopMsg.show("请选择地区!");
		} else if (StringUtils.isEmpety(city_id)) {
			PopMsg.show("请选择地区!");
		} else if (StringUtils.isEmpety(latitude) || StringUtils.isEmpety(longitude) || "0.0".equals(latitude) || "0.0".equals(longitude)) {
			PopMsg.show("请获取坐标");
		} else if (StringUtils.isEmpety(station)) {
			PopMsg.show("请填写站点信息");
		} else if (StringUtils.isEmpety(desc)) {
			PopMsg.show("请填写描述信息");
		} else {
			if (null == SelfApplication.getUserInfo() || StringUtils.isEmpety(SelfApplication.getUserInfo().getTicket())) {
				PopMsg.show("登录已过期,请重新登录");
				StartHelper.startActivity(Login.class);
			} else {
				progressDialog = ProgressDialog.show(this, "", "上报中，请稍候...", true);
				progressDialog.setCancelable(true);
				sumbit();
			}
		}
	}

	private void sumbit() {
		String wsdl_url = SelfApplication.WSDL_URL;// wsdl
		String namespace = SelfApplication.WSDL_NAME_SPACE;// namespace
		String methodName = "addHiddenDangerDanger";// 要调用的方法名称
		SoapObject request = new SoapObject(namespace, methodName);
		request.addProperty("ticket", SelfApplication.getUserInfo().getTicket());
		request.addProperty("description", desc);
		request.addProperty("latitude", latitude);
		request.addProperty("longitude", longitude);
		request.addProperty("subject", subject);
		request.addProperty("business_id", business_id);
		request.addProperty("grade_id", grade_id);
		request.addProperty("city_id", city_id);
		request.addProperty("county_id", country_id);
		request.addProperty("station_name", station);

		BuWebService webService = new BuWebService(wsdl_url, request);
		webService.setDoNet(false);
		webService.requestWSDL(new IWebService() {
			@Override
			public void logic(SoapSerializationEnvelope envelope) throws IOException, XmlPullParserException {
				SoapObject response = (SoapObject) envelope.getResponse();
				paser(response);
			}
		});
	}

	protected void paser(SoapObject soapObject) {
		Log.e("dd", soapObject.toString());
		if (null != progressDialog && progressDialog.isShowing()) {
			progressDialog.cancel();
		}
		String stauts = soapObject.getPropertySafelyAsString("status");
		SoapObject msgObjec = (SoapObject) soapObject.getProperty("msg");
		String message = msgObjec.getPropertySafelyAsString("message");
		if ("-3".equals(stauts)) {
			Message msg = new Message();
			msg.what = ERROR_MSG;
			msg.obj = message;
			handler.sendMessage(msg);
		} else if ("-2".equals(stauts)) {
			Message msg = new Message();
			msg.what = ERROR_MSG;
			msg.obj = message;
			handler.sendMessage(msg);
		} else if ("-1".equals(stauts)) {
			Message msg = new Message();
			msg.what = TO_LOGIN;
			msg.obj = message;
			handler.sendMessage(msg);
		} else if ("0".equals(stauts)) {
			Message msg = new Message();
			msg.what = TO_UPDATE_PIC;
			String[] objs = new String[] { soapObject.getPropertySafelyAsString("upload_url"), soapObject.getPropertySafelyAsString("hidden_danger_id") };
			msg.obj = objs;
			handler.sendMessage(msg);
		}

	}

	private static final int ERROR_MSG = 0x1013;
	private static final int TO_LOGIN = 0x1019;
	private static final int TO_UPDATE_PIC = 0x2010;
	Handler handler = new Handler() {

		@Override
		public void handleMessage(Message msg) {

			if (msg.what == ERROR_MSG) {
				PopMsg.show((String) msg.obj);
			} else if (msg.what == TO_LOGIN) {
				PopMsg.show((String) msg.obj);
				StartHelper.startActivity(Login.class);
			} else if (msg.what == TO_UPDATE_PIC) {
				if (fileNames.size() > 0) {
					PopMsg.show("上报成功，即将上传照片！");
					toUpLoadFile((String[]) msg.obj);
				} else {
					PopMsg.show("上报成功！");
					setResult(RESULT_OK);
					DangerSubmit.this.finish();
				}
			}
		}

	};

	private void toUpLoadFile(String[] objs) {
		Intent intent = new Intent(DangerSubmit.this, UploadPic.class);
		Bundle bundle = new Bundle();
		bundle.putStringArrayList("fileNames", fileNames);
		bundle.putString("upload_url", objs[0]);
		bundle.putString("danger_id", objs[1]);
		bundle.putString("ticket", SelfApplication.getUserInfo().getTicket());
		intent.putExtras(bundle);
		startActivityForResult(intent, REQUEST_CODE_TO_UPLOAD_PIC);
	}

	@Override
	public void topBarLogic(TopBar topBar) {
		topBar.setTitle(R.string.danger_list_submit);
		initTopBarReturn(topBar);
		topBar.setLogicBtnText("提交");
		topBar.setTopBarBtnListern(new TopBar.LogicBtnListern() {
			@Override
			public void onClickLogicBtn() {
				validationAndSubmit();
			}
		});
	}


	@Override
	protected void onActivityResult(int requestCode, int resultCode, Intent data) {
		super.onActivityResult(requestCode, resultCode, data);
		if (requestCode == REQUEST_CODE_GET_SUBJECT && resultCode == RESULT_OK) {
			Bundle bundle = data.getExtras();
			subject = bundle.getString("desc");
			danger_info_subject.setText(subject);
		} else if (requestCode == REQUEST_CODE_GET_LOACTION && resultCode == RESULT_OK) {
			Bundle bundle = data.getExtras();
			this.longitude = bundle.getString("longitude");
			this.latitude = bundle.getString("latitude");
			danger_info_location.setText(latitude + "," + longitude);
		} else if (requestCode == REQUEST_CODE_GET_DECRIPTON && resultCode == RESULT_OK) {
			Bundle bundle = data.getExtras();
			desc = bundle.getString("desc");
			danger_info_description.setText(desc);
		} else if (requestCode == REQUEST_CODE_GET_STATION && resultCode == RESULT_OK) {
			Bundle bundle = data.getExtras();
			station = bundle.getString("desc");
			danger_info_station_name.setText(station);
		} else if (requestCode == REQUEST_CODE_GET_GRADE && resultCode == RESULT_OK) {
			Bundle bundle = data.getExtras();
			grade_id = bundle.getString("grade_id");
			danger_info_grade_name.setText(bundle.getString("grade_name"));
		} else if (requestCode == REQUEST_CODE_GET_BUSINESS && resultCode == RESULT_OK) {
			Bundle bundle = data.getExtras();
			business_id = bundle.getString("business_id");
			danger_info_business_name.setText(bundle.getString("business_name"));
		} else if (requestCode == REQUEST_CODE_GET_ORG && resultCode == RESULT_OK) {
			Bundle bundle = data.getExtras();
			city_id = bundle.getString("city_id");
			country_id = bundle.getString("coutry_id");
			danger_info_city_country.setText(bundle.getString("city_courty_name"));
		} else if (requestCode == REQUEST_CODE_GET_PHOTO && resultCode == RESULT_OK) {
			Bundle bundle = data.getExtras();
			ArrayList<String> reciveredFileNames = bundle.getStringArrayList("fileNames");
			if (null != reciveredFileNames && reciveredFileNames.size() > 0) {
				fileNames.clear();
				fileNames.addAll(reciveredFileNames);
				danger_info_photo.setText(reciveredFileNames.size() + " 张照片");
			} else {
				danger_info_photo.setText("无");
			}
		} else if (requestCode == REQUEST_CODE_TO_UPLOAD_PIC && resultCode == RESULT_OK) {
			setResult(RESULT_OK);
			DangerSubmit.this.finish();
		}
	}

	@Override
	protected void onResume() {
		super.onResume();
	}
}
